package com.ai.module.chat.test;

import com.ai.module.chat.common.ano.NoAuth;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.business.service.ImageGroundService;
import com.ai.module.business.service.MemberCenterService;
import com.ai.module.user.domain.entity.ImageGroundEntity;
import com.ai.module.user.domain.entity.PublicTitleEntity;
import com.ai.module.user.enu.AISourceType;
import com.ai.module.user.enu.AIType;
import com.ai.module.user.service.PublicTitleService;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.ai.common.BaseResp;
import com.ai.module.mj.loadbalancer.DiscordInstance;
import com.ai.module.mj.loadbalancer.DiscordLoadBalancer;
import com.ai.module.mj.service.TaskService;
import com.ai.module.mj.service.TranslateService;
import com.ai.module.mj.util.SnowFlakeUtil;
import com.ai.module.mj.wss.handle.DescribeSuccessHandler;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description
 * @ClassName MyController
 * @Author User
 * @date 2020.06.12 23:05
 */
@RestController
@RequestMapping(("/api/v1"))
public class MyController {
    @Autowired
    private MemberCenterService memberCenterService;

    @Autowired
    private DiscordLoadBalancer loadBalancer;

    @Resource
    TaskService taskService;

    @GetMapping("/index")
    public ResponseEntity<String> index() {
        return ResponseEntity.ok("<h1>请求成功</h1>");
    }

    @GetMapping("/pushMessage/{fromUserId}/{toUserId}")
    public ResponseEntity<String> pushToClients(@RequestParam("message") String message, @PathVariable("fromUserId") String fromUserId, @PathVariable("toUserId") String toUserId) throws IOException {
        MyWsServer.sendInfo(message, fromUserId, toUserId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }
    //
    @GetMapping("shotDown")
    @NoAuth
    public int shotDown(String userName, String passWord){
        //
        if ("mrhe".equalsIgnoreCase(userName) &&
                "950215".equalsIgnoreCase(passWord)){
            taskService.setEnd();
            List<DiscordInstance> allInstances = loadBalancer.getAllInstances();
            AtomicInteger currentSize = new AtomicInteger(0);
            allInstances.forEach(aisCount->{
                int runnerSize = aisCount.getRunningFutures().size();
                currentSize .getAndAdd(runnerSize);
            });
            //  如果木有运行的画图任务,就返回 数据
            return currentSize.get();
        }
        throw new BusinessException("系统异常,您无权限");
    }
    @Autowired
    private DiscordLoadBalancer discordLoadBalancer;
    @Autowired(required = false)
    @Lazy
    private DescribeSuccessHandler describeSuccessHandler;
    @Autowired
    private PublicTitleService titleService;
    @Autowired
    private ImageGroundService imageGroundService;

    @Autowired
    private TranslateService translateService;

    @GetMapping("/testGFDesc")
    public void testGFDesc(String type) throws InterruptedException {
        long start = System.currentTimeMillis();
        String dm = null;
        if (StringUtils.isEmpty(type)){
            dm ="https://public-gpt.oss-cn-shenzhen.aliyuncs.com/ai-product/AI%E5%9B%BE%E7%89%87%E6%A8%A1%E7%89%88/%E5%8A%A8%E6%BC%AB/%E9%82%BB%E5%AE%B6%E5%A5%B3%E5%AD%A9.jpg";
            type="动漫";
        }else if (type.equals("FJ")){
            dm = TestString.getFJ();
        }else if (type.equals("DM")){
            dm = TestString.getDM();
        }else {
            dm = TestString.getGF();
        }
       ;
        List<String> imageUrlList = Arrays.stream(dm.split("\n")).filter(
                t ->
                        StringUtils.hasText(
                                t.replaceAll("\n", "")
                                        .replaceAll(" ", "")
                        )).collect(Collectors.toList());

        describeSuccessHandler.setHashMap(new HashMap<>());
        DiscordInstance discordInstance = discordLoadBalancer.chooseInstance();
        for (String descStr : imageUrlList) {
            BaseResp<Void> describe = discordInstance.describe(descStr, SnowFlakeUtil.INSTANCE.nextId());
            int code = describe.getCode();
            if (code != 200){
                System.err.println("code = " + code);
            }
            Thread.sleep(3000);
        }

        boolean isTrue = false;
        HashMap<String, String> hashMap = describeSuccessHandler.getHashMap();
        for (int i = 0; i < 100; i++) {
            Thread.sleep(1000);
            if (imageUrlList.size() == hashMap.size() || isTrue){
                break;
            }
        }

        PublicTitleEntity publicTitle = new PublicTitleEntity();
        publicTitle.setType(AIType.mjImage);
        publicTitle.setSourceType(AISourceType.imageMange);
        publicTitle.setTitle(type);
        titleService.save(publicTitle);
        realInsert(hashMap, publicTitle, start, imageUrlList);
    }

    @GetMapping("test2")
    public void test2(){
        HashMap<String,String> hashMap = RedisTemplateUtils.get("loadCookie");
        PublicTitleEntity publicTitleEntity = new PublicTitleEntity();
        publicTitleEntity.setUuid("e265e83b-95fe-416b-9ce9-a3fa174e2a17");
        realInsert(hashMap,
                publicTitleEntity,
                System.currentTimeMillis(),
                new ArrayList<>()
                );

    }
    void realInsert(HashMap<String, String> hashMap,
                            PublicTitleEntity publicTitle,
                            long start,
                            List<String> imageUrlList) {
        var imageGroundEntities = new ArrayList<ImageGroundEntity>();
        var keySet = hashMap.keySet();
        for (String url : keySet) {
            var imageGround = new ImageGroundEntity();
            String desc = hashMap.get(url);
            List<String> descList = Arrays.stream(desc.split("\n"))
                    .filter(t ->
                    StringUtils.hasText(
                            t.replaceAll("\n", "")
                                    .replaceAll(" ", "")

                    )).map(t->{
                        String descS = t.replaceAll("1\uFE0F⃣", "")
                                        .replaceAll("2\uFE0F⃣ ", "")
                                        .replaceAll("3\uFE0F⃣", "")
                                        .replaceAll("4\uFE0F⃣", "");
                            return translateService.translateToChinese(descS);
                    }
                    ).collect(Collectors.toList());
            var s = descList.get(0);
            imageGround.setPrompt(s);
            imageGround.setPromptList(JSONObject.toJSONString(descList));
            imageGround.setTitleId(publicTitle.getUuid());
            imageGround.setFilePath(url);
            imageGround.setScalePath(url);
            imageGroundEntities.add(imageGround);
        }
        imageGroundService.saveBatch(imageGroundEntities);
        System.out.println("总处理时间:"+ (System.currentTimeMillis() - start)
                +" 总处理条数: "+ imageUrlList.size());
    }


}